package com.hand.test.filter;/**
 * @author Estelle@앙수청
 * @date 2019/7/20 16:59
 */

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *  @author Estelle@앙수청
 *  @date 2019/7/20 16:59
 */
@Component
public class PermissionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("FilterConfig init()");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String userId = request.getHeader("userId");
        if(!StringUtils.isEmpty(userId)){
            filterChain.doFilter(request,response);
            response.setStatus(200);
        }else{
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setStatus(HttpStatus.FORBIDDEN.value());
            ErrorMsg errorMsg = new ErrorMsg("permission_not_found", "用户无权限");
            String msg = JSON.toJSONString(errorMsg);
            PrintWriter writer = response.getWriter();
            writer.print(msg);
            writer.close();
        }
    }

    @Override
    public void destroy() {
        System.out.println("FilterConfig init()");
    }
}
